package com.relife.common.file;

import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.imageio.ImageIO;

import com.relife.common.utils.StringUtil;
import org.apache.log4j.Logger;
import org.springframework.core.io.support.PropertiesLoaderUtils;


import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;

import it.sauronsoftware.jave.AudioAttributes;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncodingAttributes;

public class FileUtil {
	private static final Logger log = Logger.getLogger("FileUtil");

	public static String getFileContentType(String suffix) {
		try {
			Properties properties = PropertiesLoaderUtils.loadAllProperties("file-content-type.properties");
			return properties.getProperty(suffix);
		} catch (Exception e) {
			log.error("配置文件未配置该属性【" + suffix + "】的文件类型");
			return null;
		}
	}

	/**
	 * 保存文件
	 * 
	 * @author WU
	 * @date 2015年12月7日 上午11:09:11
	 * @param savePath
	 */
	public static void cotyFile(InputStream in, String savePath) {
		try {
			OutputStream out = new FileOutputStream(savePath);
			int bytesRead = 0;
			byte[] buffer = new byte[10240];
			while ((bytesRead = in.read(buffer, 0, 10240)) != -1) {
				out.write(buffer, 0, bytesRead);// 将文件写入服务器
			}
			out.flush();
			out.close();
			in.close();

		} catch (FileNotFoundException e) {
			log.error(e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			log.error(e.getMessage());
			e.printStackTrace();
		}
	}

	/**
	 * 获取项目物理地址
	 * 
	 * @author WU
	 * @date 2015年12月25日 下午2:16:22
	 * @return
	 */
	public static String getRealPath() {
		try {
			return Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath();
		} catch (URISyntaxException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 从文件中读取文本内容
	 * 
	 * @param file
	 *            目标文件
	 * @param encoding
	 *            目标文件的文本编码格式
	 * @return
	 * @throws IOException
	 */
	public static StringBuffer readerFile(String path, String encoding) throws IOException {
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new InputStreamReader(new FileInputStream(path), encoding));
			StringBuffer builder = new StringBuffer();
			char[] chars = new char[4096];

			int length = 0;

			while (0 < (length = reader.read(chars))) {
				builder.append(chars, 0, length);
			}
			return builder;
		} finally {
			try {
				if (reader != null) {
					reader.close();
				}

			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
	}

	/**
	 * 
	 * @author WU
	 * @date 2017年1月24日 上午11:49:04
	 * @param source
	 * @param target
	 * @return
	 * @throws Exception
	 */
	public static void wav2Mp3(String source, String target) {
		try {
			File tag = new File(target);
			if (!tag.exists()) {
				AudioAttributes audio = new AudioAttributes();
				audio.setCodec("libmp3lame");
				audio.setBitRate(new Integer(36000)); // 音频比率 MP3默认是1280000
				audio.setChannels(new Integer(2));
				audio.setSamplingRate(new Integer(44100));
				EncodingAttributes attrs = new EncodingAttributes();
				attrs.setFormat("mp3");
				attrs.setAudioAttributes(audio);
				Encoder encoder = new Encoder();
				encoder.encode(new File(source), tag, attrs);
			} else {
				log.info("文件【" + target + "】已经存在");
			}
		} catch (Exception e) {
			log.error(StringUtil.exception2String(e));
		}

	}

	public static void wav2Ogg(String source, String target) {
		try {
			File tag = new File(target);
			if (!tag.exists()) {
				AudioAttributes audio = new AudioAttributes();
				audio.setCodec("libvorbis");
				audio.setBitRate(new Integer(320000)); // 音频比率 MP3默认是1280000
				audio.setChannels(new Integer(2));
				audio.setSamplingRate(new Integer(44100));
				EncodingAttributes attrs = new EncodingAttributes();
				attrs.setFormat("ogg");
				attrs.setAudioAttributes(audio);
				Encoder encoder = new Encoder();
				encoder.encode(new File(source), tag, attrs);
			} else {
				log.info("文件【" + target + "】已经存在");
			}
		} catch (Exception e) {
			log.error(StringUtil.exception2String(e));
		}

	}

	public static void main(String[] args) {
		wav2Ogg("D:\\60120170123162003.WAV", "D:\\601201701231620038.ogg");
	}

	/** 生成二维码图片 **/
	public static void generateQrCode(String id, String savePath, int width, int height) throws Exception {
		MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
		Map hints = new HashMap();
		BitMatrix bitMatrix = multiFormatWriter.encode(id, BarcodeFormat.QR_CODE, width, height, hints);
		int BLACK = 0xFF000000;
		int WHITE = 0xFFFFFFFF;

		// 1. 创建 BufferedImage
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_INDEXED);
		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {
				image.setRGB(x, y, bitMatrix.get(x, y) ? BLACK : WHITE);
			}
		}
		// 2. 如果保存目录不存在,创建
		File folder = new File(savePath);
		if (!folder.exists()) {
			folder.mkdirs();
		}
		// 3. 生成二维码图片
		File file1 = new File(savePath, id + ".jpg");
		if (!ImageIO.write(image, "jpg", file1)) {
			throw new IOException("Could not write an image");
		}
	}
}
